<template>
  <div class="page-controller">
    <FITable
      ref="tableRef"
      class="box-radius2"
      title="记录集"
      :id="`result_${tableId}`"
      :readonly="false"
      :data="dataList"
      primaryKey="id"
      :rowNo="true"
      v-model:columns="columns"
      :insertable="true"
      :isLoading="isTableLoading"
      :saveSuccessful="saveSuccessful"
      :pageConfig="pageConfig"
      @row-add-save="addRowSave"
      @table-refresh="searchFn"
      @selection-change="handleSelectionChange"
      @size-change="handleSizeChange"
      @current-page-change="handleCurrentChange"
      @on-cell-select="selectClick"
    >
      <template #headerBtn>
        <!-- <el-button type="primary" @click="deleteRow">删除</el-button> -->
        <FIPopconfirmBtn
          title="您是否确认删除选中数据吗？"
          buttonText="删除"
          beforePopText="请选择一条数据"
          :btn-binds="{ id: 'delete', border: true }"
          @confirm="deleteRow"
          style="margin-right: 10px"
        >
        </FIPopconfirmBtn>
        <!-- <el-button type="primary" @click="importDiag = true">导入</el-button> -->
        <FIButton id="module_import" border @click="importDiag = true"></FIButton>
        <FIButton id="module_export" border @click="exportClick"></FIButton>
        <!-- <FIButton @click="menuShow = true" border style="margin-right:10px;">新增</FIButton> -->
      </template>
      <!-- <template #appCode="{ scope }">
        <FISelect
          v-if="scope.row.isSelected"
          v-model="scope.row.appCode"
          :options="appDataList"
          popperClass="select-processName-class"
          :props="{ value: 'appCode', label: 'appCode' }"
          :displayKey="['appCode', 'appName']"
          valueCustom="appCode"
          @select="selectClick($event, scope.$index, 'appCode')"
          clearable
          filterable
          usePagination
          @load-more="appCodeloadMore"
        />
        <span v-if="!scope.row.isSelected">{{ scope.row.appCode }}</span>
      </template> -->
    </FITable>
    <FIModel v-model="importDiag" width="500" title="数据权限配置导入" @confirm="uploadSure">
      <FIUpload @upload="uploadFunc"></FIUpload>
    </FIModel>
  </div>
</template>
<script lang="ts" setup>
import { reactive, onMounted, ref, computed, toRaw, defineProps, defineEmits } from 'vue'
import FITable from '@/components/FITable/index.vue'
import { apiRequestPost } from '@/api/globalApi.js'
import { ElMessage } from 'element-plus'
import { useMessage, useMessageBox } from '@/hooks/message'
import type { PageConfig, Column } from '@/types/components'
import { useRoute } from 'vue-router'
import { initSearchData } from '@/utils/common'
import { getQueryTableCache } from '@/utils/cacheUtils'
import { apiDeleteAuth, apiDeleteModule, apiSaveModule, apiQueryApp, apiImportModule } from '@/api/modules/EW.js'
const route = useRoute()
const isTableLoading = ref(false)
const importDiag = ref(false)
// 页面编码
const tableId = 'usersAudit'
// 保存成功按钮状态，默认不展示底部保存，取消按钮
const saveSuccessful = ref(false)
const tableRef = ref(null)
const appDataList = ref([])
const appCodePage = ref(1)
const loadMoreEnd = ref(false)
const emits = defineEmits(['currentChange', 'get-list', 'export-click'])
const props = defineProps({
  dataList: {
    type: Array,
    default: () => [],
  },
  pageConfig: {
    type: Object,
    default: {
      total: 0,
      currentPage: 1,
      pageSize: 10,
      currentPage: 1,
    },
  },
})

//   const pageConfig: PageConfig = reactive({
//     total: 0,
//     currentPage: 1,
//   })
const columns: Column[] = reactive([
  {
    label: '应用ID',
    prop: 'appId',
    align: 'center',
    editable: false,
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  // {
  //   label: '发起应用代码',
  //   prop: 'appCode',
  //   align: 'center',
  //   editable: true,
  //   editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  // },
  {
    label: '发起应用代码',
    prop: 'appCode',
    align: 'center',
    editable: true,
    editType: 'autoSelect',
    editConfig: {
      otherBinds: {
        apiUrl: '/bpm-service/AppCfg/queryApp',
        props: { value: 'appCode', label: 'appCode' },
        displayKey: ['appCode', 'appName'],
        searchParam: 'appQuery',
      },
    },
  },
  {
    label: '应用名称',
    prop: 'appName',
    align: 'center',
    // editable: true,
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '模块ID',
    prop: 'moduleId',
    align: 'center',
    editable: false,
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '模块代码',
    prop: 'moduleCode',
    align: 'center',
    editable: true,
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '模块名称',
    prop: 'moduleName',
    align: 'center',
    editable: true,
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '备注',
    prop: 'remark',
    align: 'center',
    editable: true,
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },

  // {
  //   label: '',
  //   prop: 'action',
  //   actionConfig: [{ id: 'isTop', type: 'top' }],
  // },
])

const checkedRows = ref([])
const uploadFile = reactive({})
//导出
const exportClick = () => {
  emits('export-click')
  // apiExportModule(state.query)
}
//应用系统查询
const queryAppFunc = () => {
  let par = {
    appCode: '',
    appName: '',
    size: 10,
    current: appCodePage.value,
  }
  apiQueryApp(par)
    .then((res) => {
      console.log(res, 'res')
      isTableLoading.value = false
      if (res.data.success) {
        // appDataList.value = res.data.data.result
        appDataList.value = appDataList.value.concat(res.data.data.result)
        if (appCodePage.value * 10 >= res.data.data.count) {
          loadMoreEnd.value = true
        }
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
      // 处理错误
    })
}

const handleSelectionChange = (e) => {
  checkedRows.value = e
}
const handleSizeChange = (e) => {
  // props.pageConfig.pageSize = e
  // props.pageConfig.currentPage = 1
  // searchFn()
}
const selectClick = (scope, item) => {
  console.log(scope, item, '查看')
  if (scope.column.property == 'appCode') {
    tableRef.value.setCellValue(scope.$index, 'appName', item.appName)
    tableRef.value.setCellValue(scope.$index, 'appId', item.appId)
  }
}
//导入
// const uploadFunc = (formData) => {
//   apiImportModule(formData)
//     .then((res) => {
//       if (res.data.success) {
//         useMessage().success(res.data.message)
//         emits('get-list')
//       }
//     })
//     .catch(() => {})
// }
//导入
const uploadFunc = (file) => {
  uploadFile.value = file
}
//点确定
const uploadSure = () => {
  const list = toRaw(uploadFile.value)
  uploadApiFn(list.raw)
}
const uploadApiFn = (file) => {
  let par = {
    file: file,
  }
  apiImportModule(par)
    .then((res) => {
      if (res.data.success) {
        useMessage().success(res.data.message)
        emits('get-list')
      }
    })
    .catch(() => {})
}
const handleSelect = (e, index) => {
  tableRef.value.setCellValue(index, 'appName', e.appName)
  // tableRef.value.setCellValue(index, 'userId', item.userId)
}
//删除事件
const deleteRow = () => {
  if (!checkedRows.value.length) {
    useMessage().warning('请选择一条数据')
    return
  }
  let ids = []
  Array.isArray(checkedRows.value) &&
    checkedRows.value.forEach((item: any) => {
      if (item?.moduleId) ids.push(item?.moduleId)
    })
  isTableLoading.value = true
  apiDeleteModule({ moduleId: ids })
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        useMessage().success(res.data.message)
        emits('get-list')
      }
    })
    .catch((error: any) => {
      useMessage().error(error.data.message)
      isTableLoading.value = false
    })
}
const handleCurrentChange = (e) => {
  emits('currentChange', e)
  // props.pageConfig.currentPage = e
  // searchFn()
}

const searchFn = (type?: string, columnsVal?: any) => {
  // const obj = initSearchData(type, columnsVal, columns, state.query)
  // state.query = obj.queryData
  // columns.values = obj.columns
  // state.query.current = pageConfig.currentPage
  // isTableLoading.value = true
  // if (pageConfig.pageSize) state.query.size = pageConfig.pageSize
  // queryAppFunc()
}
const handleSave = () => {
  isTableLoading.value = true
  saveSuccessful.value = false
  apiSaveModule(checkedRows.value)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        // saveSuccessful.value = true
        tableRef.value.clearSelection()
        emits('get-list')
      } else {
        ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
    })
}

const addRowSave = (data) => {
  handleSave()
}
onMounted(() => {
  queryAppFunc()
  // 获取查询条件缓存
  // const { cachedQuery, cachedColumns } = getQueryTableCache(route.path, tableId, state.query, columns.values)
  // if (cachedQuery) state.query = cachedQuery
  // if (columns) columns.values = cachedColumns
  // searchFn()
})
</script>
<style lang="less" scoped></style>
